package cn.cnf.service.impl;

import cn.cnf.entity.Role;
import cn.cnf.entity.User;
import cn.cnf.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhuMeiYi
 * @date 2020/12/23 17:50
 * @description
 */
@Service
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        // 调用方法查询用户
        User user = userService.findUserByUsername(username);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : userService.findRoleByUsername(username)) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), "{noop}" + user.getPassword(), authorities);
    }
}